package com.piece.core.framework.util.security.coder;

import com.piece.core.framework.util.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * Base64加密解密工具类,可反向解密
 */
@Slf4j
public class Base64Coder {

    /**
     * 加密数据
     */
    public static String encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 加密数据
     */
    public static String encode(String str) {
        return Base64.getEncoder().encodeToString(str.getBytes());
    }

    /**
     * 解密数据
     */
    public static String decode(byte[] bytes) {
        return new String(Base64.getDecoder().decode(bytes), Charset.defaultCharset());
    }

    /**
     * 解密数据
     */
    public static String decode(String str) {
        return new String(Base64.getDecoder().decode(str), Charset.defaultCharset());
    }

    /**
     * 获得图片的base64码
     */
    public static String imageToCode(String filePath) {
        if (StringUtil.isEmpty(filePath)) {
            return "";
        }
        File file = new File(filePath);
        if (!file.exists()) {
            return "";
        }
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("获取Base64图片失败：{}", e.getMessage());
        }
        if (inputStream == null) {
            return null;
        }

        return imageToCode(inputStream);
    }

    /**
     * 获得图片的base64码
     */
    public static String imageToCode(InputStream inputStream) {
        byte[] data = null;
        try {
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            log.error("读取Base64图片失败：{}", e.getMessage());
        }
        return Base64.getEncoder().encodeToString(data);
    }
}